/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * dlgAsignarPalletAUbicacion.java
 *
 * Created on 21/11/2011, 10:47:32 PM
 */

package visual.Configuracion;

import bentity.beAlmacen;
import bentity.beCombo;
import bentity.beCoordenada;
import bentity.beEntrada;
import bentity.beItem;
import bentity.beLote;
import bentity.bePallet;
import bentity.beProducto;
import bentity.beRack;
import bentity.beUbicacion;
import blogic.blAlmacen;
import blogic.blHelper;
import blogic.blProducto;
import blogic.blRack;
import blogic.blUbicacion;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import visual.Seguridad.visualHelper;

/**
 *
 * @author chokewanka
 */
public class dlgAsignarPalletAUbicacion extends javax.swing.JDialog implements KeyListener,MouseListener{
    private boolean esPrimeraVez = true;
    private BufferStrategy bfs = null;

    private beAlmacen datosAlmacen = null;
    private ArrayList<beEntrada> entradas = null;
    private blHelper blh = new blHelper();

    private ArrayList<beRack> racksSeleccionados=null;
    private ArrayList<beRack> racksDisponibles=null;
    private ArrayList<beRack> racksConTipoPallet=null;

    private Point puntoCentrado=new Point();
    private int TAM_UNIT=10;
    private int racksXCol=-1;
    private int racksXFila=-1;
    private int tamRack=-1;

    private Point puntoOrigen=new Point(70,140);
    private Point puntoFin=new Point(370, 280);

    private blRack blr=new blRack();




    @Override
    public boolean isFocusable(){
            return true;
    }

    /** Creates new form dlgAsignarPalletAUbicacion */
    public dlgAsignarPalletAUbicacion(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
                    public void mouseClicked(java.awt.event.MouseEvent evt) {
                        formMouseClicked(evt);
            }

        });

        addKeyListener(this);

        try{

            this.racksDisponibles=blr.obtenerRacks(blr.getEstados().get(1));
            this.entradas = (new blAlmacen()).buscarObjsEntrada();
            this.datosAlmacen = blh.obtenerDatosAlmacen();
            this.racksXCol=datosAlmacen.getFilas();
            this.racksXFila=datosAlmacen.getRacksXFila();
            this.tamRack=datosAlmacen.getUbsxrack();

            this.setAlwaysOnTop(true);
            this.setModal(true);

        }catch(Exception e){

        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlAlmacen = new javax.swing.JPanel();
        lblTitulo1 = new javax.swing.JLabel();
        lblCoordenadas = new javax.swing.JLabel();
        lblTipoProducto = new javax.swing.JLabel();
        lblTipoPallet = new javax.swing.JLabel();
        txtCoordenadas = new javax.swing.JTextField();
        txtTipoProducto = new javax.swing.JTextField();
        txtTipoPallet = new javax.swing.JTextField();
        btnAsignarTipoPallet = new javax.swing.JButton();
        cbxPallet = new javax.swing.JComboBox();
        lblComboPallet = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        getContentPane().setLayout(null);

        pnlAlmacen.setBackground(new java.awt.Color(178, 166, 146));

        javax.swing.GroupLayout pnlAlmacenLayout = new javax.swing.GroupLayout(pnlAlmacen);
        pnlAlmacen.setLayout(pnlAlmacenLayout);
        pnlAlmacenLayout.setHorizontalGroup(
            pnlAlmacenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 430, Short.MAX_VALUE)
        );
        pnlAlmacenLayout.setVerticalGroup(
            pnlAlmacenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 210, Short.MAX_VALUE)
        );

        getContentPane().add(pnlAlmacen);
        pnlAlmacen.setBounds(90, 90, 430, 210);

        lblTitulo1.setFont(new java.awt.Font("Dialog", 0, 36));
        lblTitulo1.setText("Asignar Tipo de Pallet a Rack");
        getContentPane().add(lblTitulo1);
        lblTitulo1.setBounds(50, 30, 620, 43);

        lblCoordenadas.setFont(new java.awt.Font("Dialog", 0, 12));
        lblCoordenadas.setForeground(new java.awt.Color(0, 0, 0));
        lblCoordenadas.setText("Coordenadas");
        getContentPane().add(lblCoordenadas);
        lblCoordenadas.setBounds(20, 390, 90, 15);

        lblTipoProducto.setFont(new java.awt.Font("Dialog", 0, 12));
        lblTipoProducto.setForeground(new java.awt.Color(0, 0, 0));
        lblTipoProducto.setText("Tipo Producto");
        getContentPane().add(lblTipoProducto);
        lblTipoProducto.setBounds(310, 390, 100, 15);

        lblTipoPallet.setFont(new java.awt.Font("Dialog", 0, 12));
        lblTipoPallet.setForeground(new java.awt.Color(0, 0, 0));
        lblTipoPallet.setText("Tipo Pallet");
        getContentPane().add(lblTipoPallet);
        lblTipoPallet.setBounds(20, 420, 100, 15);

        txtCoordenadas.setEditable(false);
        getContentPane().add(txtCoordenadas);
        txtCoordenadas.setBounds(120, 390, 170, 27);

        txtTipoProducto.setEditable(false);
        getContentPane().add(txtTipoProducto);
        txtTipoProducto.setBounds(410, 390, 170, 27);

        txtTipoPallet.setEditable(false);
        getContentPane().add(txtTipoPallet);
        txtTipoPallet.setBounds(120, 420, 170, 27);

        btnAsignarTipoPallet.setBackground(new java.awt.Color(240, 235, 226));
        btnAsignarTipoPallet.setFont(new java.awt.Font("Dialog", 0, 12));
        btnAsignarTipoPallet.setForeground(new java.awt.Color(0, 0, 0));
        btnAsignarTipoPallet.setText("Asignar");
        btnAsignarTipoPallet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAsignarTipoPalletActionPerformed(evt);
            }
        });
        getContentPane().add(btnAsignarTipoPallet);
        btnAsignarTipoPallet.setBounds(490, 350, 90, 30);

        cbxPallet.setFont(new java.awt.Font("Dialog", 0, 12));
        cbxPallet.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbxPallet.setSelectedItem(null);
        cbxPallet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxPalletActionPerformed(evt);
            }
        });
        getContentPane().add(cbxPallet);
        cbxPallet.setBounds(320, 350, 160, 25);

        lblComboPallet.setFont(new java.awt.Font("Dialog", 0, 12));
        lblComboPallet.setForeground(new java.awt.Color(0, 0, 0));
        lblComboPallet.setText("Tipo Pallet");
        getContentPane().add(lblComboPallet);
        lblComboPallet.setBounds(240, 350, 80, 15);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAsignarTipoPalletActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAsignarTipoPalletActionPerformed
        if(this.racksSeleccionados==null || this.racksSeleccionados.size()==0){
            visualHelper.mostrarMensajeAdvertencia("Seleccione uno o más racks");
            return;
        }

        ArrayList<beUbicacion> arrUbics;

        try{

        for(int i=0;i<this.racksSeleccionados.size();i++){
            arrUbics=(new blUbicacion().dameUbicacionesDeUnRack(this.racksSeleccionados.get(i).getId_rack()));

            for(int j=0;j<arrUbics.size();j++){
                //(new blUbicacion().asignarTipoPallet(arrUbics.get(j),((beItem)this.cbxPallet.getSelectedItem()).getId()));

            }
        }

        }catch(Exception e){
            e.printStackTrace();
            visualHelper.mostrarMensajeError("Ha ocurrido un error.");

        }

}//GEN-LAST:event_btnAsignarTipoPalletActionPerformed

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked

                int corX=evt.getX();
                int corY=evt.getY();
                int numCol = blh.calcularNumeroColumnas(racksXFila, tamRack);
		int numFil = blh.calcularNumeroFilas(racksXCol);

                try{

                    Point seccion=new Point();
                    seccion.x=(corX-puntoCentrado.x)/TAM_UNIT;
                    seccion.y=(corY-puntoCentrado.y)/TAM_UNIT;

                    if(corX>=puntoCentrado.x+TAM_UNIT && corX<(puntoCentrado.x-TAM_UNIT+(numCol*TAM_UNIT))
                            && corY>=puntoCentrado.y+TAM_UNIT && corY<puntoCentrado.y-TAM_UNIT+(numFil*TAM_UNIT)
                            && corX>=puntoOrigen.x && corX<puntoFin.x && corY>=puntoOrigen.y && corY<puntoFin.y){

                        Point punto=esCoordRack(seccion.x,seccion.y);
                        
                        if(punto!=null){

                            beRack rackSeleccionado=null;

                            rackSeleccionado=blr.obtenerRack(blr.getIdRackByXY(punto.x, punto.y));

                            if(estaEnElArreglo(rackSeleccionado,this.racksSeleccionados)){
                                this.racksSeleccionados.remove(rackSeleccionado);

                                setearValores();

                                repaint();
                                return;
                            }

                            this.racksSeleccionados.add(rackSeleccionado);

                            this.txtTipoProducto.setText((new blProducto().devuelveTipoProducto(rackSeleccionado.getId_tipo_producto()).getDescripcion()));

                            repaint();
                        }
                        //System.out.println(this.numCol + " "+this.getNumFil()+" "+corX+" "+ corY);
                    }

                }catch(Exception e){
                    e.printStackTrace();
                    visualHelper.mostrarMensajeError("Ocurrio un error");
                }

    }//GEN-LAST:event_formMouseClicked

    private void cbxPalletActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxPalletActionPerformed
        
        repaint();
}//GEN-LAST:event_cbxPalletActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgAsignarPalletAUbicacion dialog = new dlgAsignarPalletAUbicacion(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }


    @Override
    public void paint(Graphics g){
        //ArrayList<beUbicacion> arrAux=null;

        try{
            if (this.esPrimeraVez){
                this.esPrimeraVez=false;
                this.createBufferStrategy(2);
                bfs =this.getBufferStrategy();
            }
            if (bfs != null){
                Graphics g1=bfs.getDrawGraphics();
                super.paint(g1);

                visualHelper.pintarAlmacenConEntradasCOPIA(g1, entradas, racksXCol, racksXFila, tamRack, TAM_UNIT, this.puntoCentrado,this.puntoOrigen,this.puntoFin, Color.BLUE);

                if(this.racksDisponibles!=null)
                  visualHelper.pintarSeccionesSegunColor(g1, racksXCol, racksXFila, tamRack, TAM_UNIT, this.racksDisponibles, this.puntoCentrado,this.puntoOrigen,this.puntoFin, Color.GREEN);

                if(this.racksConTipoPallet!=null)
                  visualHelper.pintarSeccionesSegunColor(g1, racksXCol, racksXFila, tamRack, TAM_UNIT, this.racksConTipoPallet, this.puntoCentrado,this.puntoOrigen,this.puntoFin, Color.RED);

                if(this.racksSeleccionados!=null)
                  visualHelper.pintarSeccionesSegunColor(g1, racksXCol, racksXFila, tamRack, TAM_UNIT, this.racksSeleccionados, this.puntoCentrado,this.puntoOrigen,this.puntoFin, Color.YELLOW);

                visualHelper.pintarMallaCOPIA(g1,datosAlmacen.getFilas(), datosAlmacen.getRacksXFila(), datosAlmacen.getUbsxrack(),TAM_UNIT, this.puntoCentrado,this.puntoOrigen,this.puntoFin);

                bfs.show();
            }

        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("Ocurrió un error al pintar el mapa");
        }
    }

    private Point esCoordRack(int x,int y){
        
        for(int i=0;i<this.racksDisponibles.size();i++){
            int xR=2+((((beRack)this.racksDisponibles.get(i)).getNumRack())-1)*(tamRack+1);
            int yR=this.racksDisponibles.get(i).getNumFila();
            yR=visualHelper.transformarY(y);
            xR=this.puntoCentrado.x+xR*TAM_UNIT;
            yR=this.puntoCentrado.y+yR*TAM_UNIT;

            if((x>=xR && x<=(xR+tamRack*TAM_UNIT)) && yR==y){
               for(int j=0;j<tamRack;j++){
                    if(x==(xR+i)) return new Point(xR-puntoCentrado.x,yR-puntoCentrado.y);
               }
            }
        }
        return null;


    }

    private boolean estaEnElArreglo(beRack rk,ArrayList<beRack> arr){
        if(arr==null) return false;

        for(int i=0;i<arr.size();i++){
            if(arr.get(i).getId_rack()==rk.getId_rack()) return true;
        }
        return false;
    }

    private void setearValores() {
        this.txtTipoPallet.setText("");
        this.txtTipoProducto.setText("");
        this.txtCoordenadas.setText("");
    }

    private void llenarComboPallet() throws Exception{
        int maxPiso=0;
        beCoordenada c=new beCoordenada();

        maxPiso=(new blRack().obtenerRack(1).getCantPiso());

        if(maxPiso>0){
            ArrayList<beCombo> comboPiso = new ArrayList<beCombo>();
            beCombo cmb = new beCombo();
            for (int i = 0; i < maxPiso; i++) {
                cmb = new beCombo();
                cmb.setId_dato(i);
                cmb.setNom_dato(String.valueOf(i+1));
                cmb.setNom_combo("PISORK");
                comboPiso.add(cmb);
            }
            this.cbxPallet.setModel(blh.ComboBoxItem(comboPiso));
        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAsignarTipoPallet;
    private javax.swing.JComboBox cbxPallet;
    private javax.swing.JLabel lblComboPallet;
    private javax.swing.JLabel lblCoordenadas;
    private javax.swing.JLabel lblTipoPallet;
    private javax.swing.JLabel lblTipoProducto;
    private javax.swing.JLabel lblTitulo1;
    private javax.swing.JPanel pnlAlmacen;
    private javax.swing.JTextField txtCoordenadas;
    private javax.swing.JTextField txtTipoPallet;
    private javax.swing.JTextField txtTipoProducto;
    // End of variables declaration//GEN-END:variables

    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void keyPressed(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void mouseClicked(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void mousePressed(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void mouseReleased(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void mouseEntered(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void mouseExited(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }



}
